import { Component, Input, OnDestroy, OnInit, SimpleChanges, OnChanges, ViewChild, ElementRef } from '@angular/core';
import { ToolsService } from 'app/shared/service';
import { CdkDragDrop } from '@angular/cdk/drag-drop';
import { TranslateService } from '@ngx-translate/core';
import { Subscription } from 'rxjs';

@Component({
    selector: 'itmp-plan-msg-info',
    templateUrl: './plan-msg-info.component.html',
    styleUrls: ['../../../dissemination-management/message-library/add-vms/vms-message-info/vms-message-info.component.css']
})
export class PlanMsgInfoComponent implements OnInit, OnDestroy, OnChanges {
    @ViewChild('viewpoint') viewpointRef: ElementRef;
    @Input() initDisplayMessage;
    categoryId: any; // 消息类型名
    messageName: any; // 图库名称
    selectedValue = {
        messageCategory: null
    };
    selectionList = {
        messageCategory: ['Accident(main carriageway)']
    };
    containerStyle = {
        width: '320px',
        height: '32px'
    };
    title = null;
    pageUndo: any = []; // 撤销
    pageRedo: any = []; // 恢复
    contentCss: string;
    editTextSeq = null;
    text: null;
    contentStyleList: any;
    allList = {
        fontSize: [
            { value: 16, name: '16font', style: '16px' },
            { value: 24, name: '24font', style: '32px' },
            { value: 32, name: '32font', style: '48px' },
            { value: 48, name: '48font', style: '64px' }
        ],
        color: [
            { value: 1, name: 'white', style: 'white' },
            { value: 2, name: 'green', style: '#00ff01' },
            { value: 3, name: 'red', style: '#fe0000' },
            { value: 4, name: 'yellow', style: '#ffff01' },
            { value: 5, name: 'blue', style: '#0000fe' },
            { value: 6, name: 'bluish green', style: '#01ffff' },
            { value: 7, name: 'purple', style: '#ff00fe' }
        ],
        lettSpacing: [
            { value: 1, name: '1spacing', style: '1px' },
            { value: 2, name: '2spacing', style: '2px' },
            { value: 3, name: '3spacing', style: '3px' },
            { value: 4, name: '4spacing', style: '4px' },
            { value: 5, name: '5spacing', style: '4px' },
            { value: 6, name: '6spacing', style: '4px' }
        ]
    };
    deafultMsg = 'Input Text Hear...';
    subscription: Subscription = null;

    addService = {
        displayMessage: null,
        showPage: 0,
        selectGraphics: null,
        selectionList: {
            messageCategory: []
        }
    };

    constructor(private toolsService: ToolsService, private translateService: TranslateService) {}

    ngOnInit() {
        this.translate('DisseminationManagement.MessageLibrary.Input_Text_Hear').subscribe(value => {
            this.deafultMsg = value;
        });

        if (this.initDisplayMessage) {
            // this.setDisplayMessage(JSON.parse(JSON.stringify(this.initDisplayMessage)))
            this.setDisplayMessage(this.initDisplayMessage);
        }
    }

    ngOnChanges(changes: SimpleChanges): void {
        if (changes.initDisplayMessage && changes.initDisplayMessage.currentValue) {
            this.setDisplayMessage(changes.initDisplayMessage.currentValue);
        }
    }

    ngOnDestroy(): void {
        if (this.subscription) {
            this.subscription.unsubscribe();
        }
    }

    setContentStyleList() {
        const { displayMessage } = this.addService;
        this.contentStyleList = [];
        this.categoryId = displayMessage.category.categoryId;
        this.messageName = displayMessage.msgName;
        displayMessage.templatePages.forEach((pages, index) => {
            this.contentStyleList.push([]);
            const cWidth = displayMessage.deviceInfo.width;
            const cHeight = displayMessage.deviceInfo.height;
            /*if (pages.templateGraphics) {
                pages.templateGraphics.forEach((value, i) => {
                    textWidth = displayMessage.deviceInfo.width - value.graphicAreaW;
                    textHeight = displayMessage.deviceInfo.height - value.graphicAreaH;
                });
            }*/
            if (pages.templateTexts && pages.templateTexts.length) {
                const textAreaY = pages.templateTexts[0].textAreaY;
                const textHeight = (cHeight - textAreaY - 2) / pages.templateTexts.length;
                pages.templateTexts.forEach((item, idx) => {
                    let params;
                    const data = pages.texts[idx];
                    const lang = localStorage.getItem('itmp_lang');
                    if (data) {
                        params = {
                            // text: data.text || this.deafultMsg,
                            text:
                                lang === 'en' ? data.text || 'Text...' : lang === 'zh' ? data.text || '文本...' : data.text || 'Bản văn...',
                            style: {
                                // 'font-size': '16px',
                                'font-size': data.font,
                                color: data.foreColor,
                                // color: 'white',
                                'letter-spacing': data.charSpacing,
                                left: data.textAreaX + 'px',
                                top: data.textAreaY + 'px',
                                // width: item.width + 'px',
                                // height: item.height + 'px'
                                width: cWidth - data.textAreaX - 2 + 'px',
                                height: textHeight + 'px',
                                padding: 0
                            },
                            limit: {
                                maxChars: item.maxChars
                            }
                        };
                    } else {
                        params = {
                            // text: this.deafultMsg,
                            text: lang === 'en' ? 'Text...' : lang === 'zh' ? '文本...' : 'Bản văn...',
                            // text: 'Text...',
                            style: {
                                'font-size': item.font + 'px',
                                // 'font-size': '16px',
                                // color: 'white',
                                color: this.allList['color'][0].style,
                                // color: this.allList['color'][item.foreColor] && this.allList['color'][item.foreColor].style,
                                'letter-spacing': this.allList['lettSpacing'][item.charSpacing].style,
                                left: item.textAreaX + 'px',
                                top: item.textAreaY + 'px',
                                // width: item.width + 'px',
                                // height: item.height + 'px'
                                width: cWidth - item.textAreaX - 2 + 'px',
                                height: textHeight + 'px',
                                padding: 0
                            },
                            limit: {
                                maxChars: item.maxChars
                            }
                        };
                    }
                    this.contentStyleList[index].push(params);
                });
            }
        });
        this.containerStyle = {
            width: displayMessage.deviceInfo.width + 'px',
            height: displayMessage.deviceInfo.height + 'px'
        };
    }

    translate(text) {
        return this.translateService.get(text);
    }

    init() {
        this.contentCss = this.addService.displayMessage.templatePages[0].align || 'flex-start';
        this.pageUndo = [];
        this.pageRedo = [];
    }

    // 对齐方式
    align(flag, param, width) {
        this.pageUndo.push({
            type: 'style',
            page: this.addService.showPage,
            val: this.contentCss
        });
        if (flag === 'flex-start') {
            param.forEach(item => {
                item.style['text-align'] = 'left';
            });
        } else if (flag === 'center') {
            param.forEach(item => {
                item.style['text-align'] = 'center';
            });
        } else {
            param.forEach(item => {
                item.style['text-align'] = 'right';
            });
        }
        this.contentCss = flag;
    }

    // 储存改变前的数据
    changeData(flag) {
        this.pageUndo.push({
            type: 'data',
            page: this.addService.showPage,
            val: flag
        });
    }

    goToPage(page) {
        this.addService.showPage = page;
        const temp = this.addService.displayMessage.templatePages[page].text;
        this.title = temp ? temp.text : null;
    }

    // 撤销
    undo() {
        if (this.pageUndo.length < 1) {
            return;
        }
        this.pageRedo.push({
            ...this.pageUndo[this.pageUndo.length - 1]
        });
        this.addService.showPage = this.pageUndo[this.pageUndo.length - 1].page;
        if (this.pageUndo[this.pageUndo.length - 1].type === 'style') {
            this.contentCss = this.pageUndo[this.pageUndo.length - 1].val;
        } else {
            this.updateTemplatePages(this.addService.showPage, this.pageUndo[this.pageUndo.length - 1].val);
        }
        this.pageUndo.splice(this.pageUndo.length - 1, 1);
    }

    // 恢复
    redo() {
        if (this.pageRedo.length < 1) {
            return;
        }
        this.pageUndo.push({
            ...this.pageRedo[this.pageRedo.length - 1]
        });
        this.addService.showPage = this.pageRedo[this.pageRedo.length - 1].page;
        if (this.pageRedo[this.pageRedo.length - 1].type === 'style') {
            this.contentCss = this.pageRedo[this.pageRedo.length - 1].val;
        } else {
            this.updateTemplatePages(this.addService.showPage, this.pageRedo[this.pageRedo.length - 1].val);
        }
        this.pageRedo.splice(this.pageRedo.length - 1, 1);
    }

    // 拖放
    drop(event: CdkDragDrop<string[]>) {
        this.changeData(this.toolsService.isClone(this.addService.displayMessage.templatePages[this.addService.showPage]));
        const page = this.addService.displayMessage.templatePages[this.addService.showPage];
        if (event.previousContainer.id === 'graphicsContainer') {
            const index = event.container.id[16];
            page.graphics[index] = {
                messageId: null,
                graphicSeq: this.addService.showPage + 1,
                vmsGraphic: this.addService.selectGraphics
            };
        } else {
            const curIndex = event.container.id[16];
            const preIndex = event.previousContainer.id[16];
            const temp = page.graphics[curIndex];
            page.graphics[curIndex] = page.graphics[preIndex];
            page.graphics[preIndex] = temp;
        }
    }

    setCategory() {
        this.addService.selectionList.messageCategory.forEach(item => {
            if (item.categoryId === this.categoryId) {
                this.addService.displayMessage.category.categoryId = item.categoryId;
                this.addService.displayMessage.msgName = item.categoryName;
                this.categoryId = this.addService.displayMessage.category.categoryId;
                this.messageName = this.addService.displayMessage.msgName;
            }
        });
    }

    // text编辑
    startEdit(id, event, first, second) {
        if (
            this.contentStyleList[first][second].text === 'Text...' ||
            this.contentStyleList[first][second].text === '文本...' ||
            this.contentStyleList[first][second].text === 'Bản văn...'
        ) {
            this.contentStyleList[first][second].text = '';
        }
        // this.contentStyleList[text].text = ''
        event.preventDefault();
        event.stopPropagation();
        // const theText = this.addService.displayMessage.templatePages[this.addService.showPage].texts[id];
        // this.text = theText ? theText.text : '';
        this.editTextSeq = id;
    }

    // 保存文本编辑
    // saveText(seq, e) {
    //     e.preventDefault();
    //     e.stopPropagation();
    //     if (this.editTextSeq === null) {
    //         return;
    //     }
    //     if (seq === -1 || e.keyCode === 13) {
    //         this.addService.displayMessage.templatePages[this.addService.showPage].texts[this.editTextSeq]['text'] = this.text === '' ? null : this.text;
    //         this.editTextSeq = null;
    //     }
    // }

    stopPropagation(event) {
        event.preventDefault();
        event.stopPropagation();
    }

    /**modify  */
    updateTemplatePages(index, data) {
        this.addService.displayMessage.templatePages[index] = data;
    }

    setDisplayMessage(data) {
        this.addService.showPage = 0;
        this.addService.displayMessage = data;
        this.setContentStyleList();
        this.init();
    }

    setShowPage(page) {
        this.addService.showPage = page;
    }

    handleBlur(e) {
        const displayText = this.addService.displayMessage.templatePages[this.addService.showPage].texts[this.editTextSeq];
        const contentText = this.contentStyleList[this.addService.showPage][this.editTextSeq];
        displayText['text'] = contentText.text;
        this.editTextSeq = null;
    }
}
